package javabasics.concurrent.threadpool;

import java.util.List;
import java.util.Vector;

/**
 * @Author suxiaoxiao
 * @Date 2019/6/16 17:29
 * @Version 1.0
 */
public class ThreadPool {

    private static ThreadPool instance = null;

    /**
     * 空闲的线程队列
     */
    private List<PThread> idleThreads;

    /**
     * 已有的线程总数
     */
    private int threadCounter;
    private boolean isShutDown = false;

    private ThreadPool() {
        this.idleThreads = new Vector<>(5);
        threadCounter = 0;
    }

    /**
     * 获取线程总数
     * @return
     */
    public int getCreatedThreadsCount() {
        return threadCounter;
    }

    /**
     * 取的线程池的实例
     * 单例模式
     * @return
     */
    public synchronized static ThreadPool getInstance() {
        if (instance == null) {
            instance = new ThreadPool();
        }
        return instance;
    }

    /**
     * 将线程放入池中
     * @param repoolingThread
     */
    protected synchronized void repool(PThread repoolingThread) {
        if (!isShutDown) {
            idleThreads.add(repoolingThread);
        } else {

        }
    }

    /**
     * 停止池中所有线程
     */
    public synchronized void shutdown() {
        isShutDown = true;
        for (int threadIndex = 0; threadIndex < idleThreads.size(); threadIndex++) {
            PThread idleThread = idleThreads.get(threadIndex);
            idleThread.shutDown();
        }
    }

    public synchronized void start(Runnable target) {
        PThread thread = null;
        if (idleThreads.size() > 0) {
            int lastIndex = idleThreads.size() - 1;
            thread = idleThreads.get(lastIndex);
            idleThreads.remove(lastIndex);
            // 执行这个任务
            thread.setTarget(target);
        } else {
            // 没有空闲线程，则创建新线程。
            threadCounter++;
            // 创建新线程
            thread = new PThread(target, "PTthread # " + threadCounter, this);
            // 启动这个线程
            thread.start();
        }
    }

}
